package wangn;

import wangn.adt.CFG;
import wangn.adt.ItemSetNode;
import wangn.adt.lrparsing.RootNode;
import wangn.procedure.LRItemTree;
import wangn.procedure.LRParsingTable;
import wangn.procedure.Matching;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

//启动类，并且这里统一处理错误或者异常
public class Main {
    /**
     *
     * @param grammarFile 需要匹配的文法
     * @param matchTextFile 需要匹配的字符实例
     * @return boolean TRUE没有错误 FALSE发现错误
     */
    public boolean syntaxAnalyze(File grammarFile, File matchTextFile){
        if (!grammarFile.exists() || !matchTextFile.exists())return false;

        String grammar = readFile(grammarFile);
        String matchText = readFile(matchTextFile);

        //产生式
        CFG cfg = CFG.getInstance(grammar);

        //LR项集
        LRItemTree lrItemTree = new LRItemTree();
        ItemSetNode lrItemSetRoot = lrItemTree.constructLRItemTree(cfg);

        //LR分析表
        LRParsingTable lrParsingTable = new LRParsingTable();
        RootNode lrItemTableRoot = lrParsingTable.constructLRParsingTable(cfg,lrItemSetRoot);

        //进行匹配工作
        Matching matching = new Matching();
        matching.match(cfg, lrItemTableRoot,matchText);

        return true;
    }

    private String readFile(File file){
        String tmp = "";
        StringBuilder sb = new StringBuilder();
        try(BufferedReader br = new BufferedReader(new FileReader(file))){
            while ((tmp=br.readLine())!=null){
                sb.append(tmp);
                sb.append('\n');
            }
            sb.deleteCharAt(sb.lastIndexOf("\n"));
        }catch (Exception e){
            e.printStackTrace();
        }
        return sb.toString();
    }
}
